package com.pxst.agent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.pxst.agent.entity.*;
import com.pxst.agent.mapper.*;
import com.pxst.agent.req.ProgressionReq;
import com.pxst.agent.req.RebateCreateReq;
import com.pxst.agent.req.RebateReq;
import com.pxst.agent.req.RegularReq;
import com.pxst.agent.resp.*;
import com.pxst.agent.service.SysRebateSchemeService;
import com.pxst.resp.ApiResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* @author zarke
* @since 2023-09-12 15:21:03
*/
@Service
@Transactional
@Slf4j
public class SysRebateSchemeServiceImpl extends ServiceImpl<SysRebateSchemeMapper, SysRebateScheme> implements SysRebateSchemeService {

    @Autowired
    private SysRebateSchemeMapper sysRebateSchemeMapper;

    @Autowired
    private SysRebateProgressionMapper sysRebateProgressionMapper;

    @Autowired
    private SysRebateRegularMapper sysRebateRegularMapper;

    @Autowired
    private SysAgentCommissionSettingsMapper sysAgentCommissionSettingsMapper;

    @Autowired
    private SysAgentsMapper sysAgentsMapper;

    /**
     * 回扣方案下拉框信息
     * @return
     */
    @Override
    public ApiResp<RebateInfo> getRebateInfo() {
        List<SysRebateScheme> sysRebateSchemes = sysRebateSchemeMapper.selectList(null);
        List<RebateInfo> collect = sysRebateSchemes.stream().map(iter -> {
            RebateInfo rebateInfo = new RebateInfo();
            BeanUtils.copyProperties(iter, rebateInfo);
            return rebateInfo;
        }).collect(Collectors.toList());
        return ApiResp.sucess(collect);
    }

    /**
     * 回扣方案下拉框信息
     * @return
     */
    @Override
    public ApiResp<RebateBydetails> getRebateByDetails() {
        List<SysRebateScheme> sysRebateSchemes = sysRebateSchemeMapper.selectList(null);

        List<RebateBydetails> collect = sysRebateSchemes.stream().map(iter -> {
            RebateBydetails rebateBydetails = new RebateBydetails();
            BeanUtils.copyProperties(iter, rebateBydetails);
            if (iter.getType() != null && iter.getType() == 1) {
                LambdaQueryWrapper<SysRebateProgression> plqw = new LambdaQueryWrapper<>();
                plqw.eq(SysRebateProgression::getRsId, iter.getRsId());
                List<SysRebateProgression> sysRebateProgressions = sysRebateProgressionMapper.selectList(plqw);
                rebateBydetails.setDetails(sysRebateProgressions);
            } else if (iter.getType() != null && iter.getType() == 2) {
                LambdaQueryWrapper<SysRebateRegular> rlqw = new LambdaQueryWrapper<>();
                rlqw.eq(SysRebateRegular::getRsId, iter.getRsId());
                List<SysRebateRegular> sysRebateRegularList = sysRebateRegularMapper.selectList(rlqw);
                rebateBydetails.setDetails(sysRebateRegularList);
            }
            return rebateBydetails;
        }).collect(Collectors.toList());
        return ApiResp.sucess(collect);
    }

    /**
     * 搜索
     * @param rebateReq
     * @return
     */
    @Override
    public ApiResp<RebateListResp> getRebateList(RebateReq rebateReq) {
        //首先通过name，type条件查询sys_rebate_scheme（回扣方案）
        LambdaQueryWrapper<SysRebateScheme> lqw = new LambdaQueryWrapper<>();
        if (rebateReq.getName() != null && !rebateReq.getName().isEmpty()){
            lqw.eq(SysRebateScheme::getName,rebateReq.getName());
        }
        if (rebateReq.getType() != null){
            lqw.eq(SysRebateScheme::getType,rebateReq.getType());
        }
        PageHelper.startPage(rebateReq.getPage(),rebateReq.getRp());
        Page<SysRebateScheme> page = (Page<SysRebateScheme>)sysRebateSchemeMapper.selectList(lqw);

        List<RebateListResp> collect = page.getResult().stream().map(iter -> {
            RebateListResp rebateListResp = new RebateListResp();
            BeanUtils.copyProperties(iter, rebateListResp);
            //details字段处理：判断type的不同值来关联查询不同的表
            if (iter.getType() != null && iter.getType() == 1) {
                //当type=1时，关联查询sys_rebate_progression（累进式回扣方案）
                List<SysRebateProgression> sysRebateProgressions = sysRebateProgressionMapper.selectList(new LambdaQueryWrapper<SysRebateProgression>()
                        .eq(SysRebateProgression::getRsId, iter.getRsId()));
                if (sysRebateProgressions != null && sysRebateProgressions.size() > 0) {
                    rebateListResp.setDetails(sysRebateProgressions);
                }
            } else if (iter.getType() != null && iter.getType() == 2) {
                //当type=2时，关联查询system_rebate_regular（固定式回扣方案）
                List<SysRebateRegular> sysRebateRegularList = sysRebateRegularMapper.selectList(new LambdaQueryWrapper<SysRebateRegular>()
                        .eq(SysRebateRegular::getRsId, iter.getRsId()));
                if (sysRebateRegularList != null && sysRebateRegularList.size() > 0) {
                    rebateListResp.setDetails(sysRebateRegularList);
                }
            }
            //agents字段处理：通过rs_id关联查询sys_agent_commission_settings（抽成设定表）的信息，得到代理id，再通过代理id查询sys_agents（代理信息）。
            List<SysAgentCommissionSettings> sysAgentCommissionSettings = sysAgentCommissionSettingsMapper.selectList(new LambdaQueryWrapper<SysAgentCommissionSettings>()
                    .eq(SysAgentCommissionSettings::getBdrsRpId, iter.getRsId())
                    .or()
                    .eq(SysAgentCommissionSettings::getQdrsRpId, iter.getRsId())
//                    .or()
//                    .eq(SysAgentCommissionSettings::getLbdrsRpId, iter.getRsId())
//                    .or()
//                    .eq(SysAgentCommissionSettings::getTwdrsRpId, iter.getRsId())
                    .or()
                    .eq(SysAgentCommissionSettings::getWrsRpId, iter.getRsId()));
            if (sysAgentCommissionSettings != null && sysAgentCommissionSettings.size() > 0) {
                List<Long> agentIds = sysAgentCommissionSettings.stream()
                        .map(SysAgentCommissionSettings::getAgentId)
                        .filter(Objects::nonNull)
                        .distinct()
                        .collect(Collectors.toList());
                if (agentIds.size() > 0) {
                    List<SysAgents> sysAgents = sysAgentsMapper.selectBatchIds(agentIds);
                    if (sysAgents != null && sysAgents.size() > 0) {
                        //在返回类中保存代理信息
                        List<AgentByIdResp> agentByIdRespList = sysAgents.stream().map(iter1 -> {
                            AgentByIdResp agent = new AgentByIdResp();
                            BeanUtils.copyProperties(iter1, agent);
                            return agent;
                        }).collect(Collectors.toList());
                        rebateListResp.setAgents(agentByIdRespList);
                    }
                }
            }
            return rebateListResp;
        }).collect(Collectors.toList());
        return ApiResp.page(page.getPageNum(), page.getPageSize() , (int) page.getTotal(), collect);
    }

    /**
     * 新增方案
     * @param rebateReq
     * @return
     */
    @Override
    public ApiResp<RebateCreateResp> createRebate(RebateCreateReq rebateReq) {
        //判断type的值，决定是什么方案再进行存值
        SysRebateScheme sysRebateScheme = new SysRebateScheme();
        BeanUtils.copyProperties(rebateReq,sysRebateScheme);
        sysRebateSchemeMapper.insert(sysRebateScheme);
        //创建返回类
        RebateCreateResp rebateCreateResp = new RebateCreateResp();
        SysRebateScheme rebateScheme = sysRebateSchemeMapper.selectById(sysRebateScheme.getRsId());
        BeanUtils.copyProperties(rebateScheme,rebateCreateResp);
        rebateCreateResp.setDetails(rebateReq.getDetails());
        // 获取当前时间的毫秒数
        long currentTimeMillis = System.currentTimeMillis();
        // 使用毫秒数创建 Timestamp 对象
        Timestamp currentTimestamp = new Timestamp(currentTimeMillis);

        if (rebateReq.getType() != null && rebateReq.getType() == 1){
            //当type=1时，（累进式回扣方案）
            List<ProgressionReq> list = new ArrayList<>();
            for (Object detail : rebateReq.getDetails()) {
                ProgressionReq progressionReq = new ProgressionReq();
                LinkedHashMap<String,String> detail1 = (LinkedHashMap) detail;
                for (Map.Entry<String, String> stringStringEntry : detail1.entrySet()) {
                    String key = stringStringEntry.getKey();
                    Object value = stringStringEntry.getValue();

                    if (value != null){
                        switch (key){
                            case"from":
                                BigDecimal from = new BigDecimal(value.toString());
                                progressionReq.setFrom(from);
                                break;
                            case "rate":
                                progressionReq.setRate(Double.valueOf(value.toString()));
                                break;
                            case "to":
                                BigDecimal to = new BigDecimal(value.toString());
                                progressionReq.setTo(to);
                                break;
                            default:
                                return ApiResp.bussError("参数有误");
                        }
                    }
                }
                list.add(progressionReq);
            }
            for (ProgressionReq detail : list) {
                SysRebateProgression sysRebateProgression = new SysRebateProgression();
                BeanUtils.copyProperties(detail,sysRebateProgression);
                sysRebateProgression.setCreatedAt(currentTimestamp);
                sysRebateProgression.setUpdatedAt(currentTimestamp);
                sysRebateProgression.setRsId(sysRebateScheme.getRsId());
                sysRebateProgressionMapper.insert(sysRebateProgression);
            }
            return ApiResp.sucess(rebateCreateResp);
        }else if (rebateReq.getType() != null && rebateReq.getType() == 2){
            //当type=2时，（固定式回扣方案）
            List<RegularReq> list = new ArrayList<>();
            for (Object detail : rebateReq.getDetails()) {
                RegularReq regularReq = new RegularReq();
                LinkedHashMap<String,String> detail1 = (LinkedHashMap) detail;
                for (Map.Entry<String, String> stringStringEntry : detail1.entrySet()) {
                    String key = stringStringEntry.getKey();
                    Object value = stringStringEntry.getValue();

                    if (value != null){
                        switch (key){
                            case "volume":
                                BigDecimal from = new BigDecimal(value.toString());
                                regularReq.setVolume(from);
                                break;
                            case "rate":
                                regularReq.setRate(Double.valueOf(value.toString()));
                                break;
                            default:
                                return ApiResp.bussError("参数有误");
                        }
                    }
                }
                list.add(regularReq);
            }
            for (RegularReq detail : list) {
                SysRebateRegular sysRebateRegular = new SysRebateRegular();
                BeanUtils.copyProperties(detail, sysRebateRegular);
                sysRebateRegular.setCreatedAt(currentTimestamp);
                sysRebateRegular.setUpdatedAt(currentTimestamp);
                sysRebateRegular.setRsId(sysRebateScheme.getRsId());
                sysRebateRegularMapper.insert(sysRebateRegular);
            }
            return ApiResp.sucess(rebateCreateResp);
        }else {
            return ApiResp.bussError("参数有误");
        }
    }

    /**
     * 方案详情
     * @param id
     * @return
     */
    @Override
    public ApiResp<RebateCreateResp> getRebateById(Long id) {
        //查询出方案信息，判断type的值，再联查具体方案的详细详细
        SysRebateScheme sysRebateScheme = sysRebateSchemeMapper.selectById(id);
        RebateCreateResp rebateCreateResp = new RebateCreateResp();
        BeanUtils.copyProperties(sysRebateScheme,rebateCreateResp);
        //details字段处理：判断type的不同值来关联查询不同的表
        if (sysRebateScheme.getType() != null && sysRebateScheme.getType() == 1) {
            //当type=1时，关联查询sys_rebate_progression（累进式回扣方案）
            List<SysRebateProgression> sysRebateProgressions = sysRebateProgressionMapper.selectList(new LambdaQueryWrapper<SysRebateProgression>()
                    .eq(SysRebateProgression::getRsId, sysRebateScheme.getRsId()));
            if (sysRebateProgressions != null && sysRebateProgressions.size() > 0) {
                rebateCreateResp.setDetails(sysRebateProgressions);
            }
        } else if (sysRebateScheme.getType() != null && sysRebateScheme.getType() == 2) {
            //当type=2时，关联查询system_rebate_regular（固定式回扣方案）
            List<SysRebateRegular> sysRebateRegularList = sysRebateRegularMapper.selectList(new LambdaQueryWrapper<SysRebateRegular>()
                    .eq(SysRebateRegular::getRsId, sysRebateScheme.getRsId()));
            if (sysRebateRegularList != null && sysRebateRegularList.size() > 0) {
                rebateCreateResp.setDetails(sysRebateRegularList);
            }
        }
        return ApiResp.sucess(rebateCreateResp);
    }

}